﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using System.Drawing;
using System.IO;
using System.Net.Http.Headers;
using RestFullChatAJAX.Models;
using System.Text;

namespace RestFullChatAJAX.Controllers
{
    public class PictureController : ApiController
    {
        // GET api/Picture/username
        public HttpResponseMessage GetPicture(String id)
        {
            byte[] img = null;
            try
            {
                img = File.ReadAllBytes(Utility.Root + "Images/" + id + ".jpg");
            }
            catch (Exception ex)
            {
                img = File.ReadAllBytes(Utility.Root + "Images/anonymous.png");
            }
            if (null == img)
                return null;
            var result = new HttpResponseMessage();
            result.Content = new ByteArrayContent(img);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            return result;
        }

        //Post api/Picture/username?ar
        public HttpStatusCode PostPicture(String id,[FromBody]byte[] picture)
        {
            /*String base64 = picture.Content;
            Byte[] img = new Byte[base64.Length];
            img = Convert.FromBase64String(FixBase64ForImage(base64).Trim('\0'));*/
            byte[] img = picture;
             
            if (null == img)
                return HttpStatusCode.BadRequest;
            try
            {
                //Create image
                String path = Utility.Root + "Images/" + id.Trim() + ".jpg";
                Image pic = Utility.byteArrayToImage(img);
                pic.Save(path);
            }
            catch (Exception ex)
            {
                return HttpStatusCode.BadRequest;
            }
            return HttpStatusCode.OK;
        }

        public static string FixBase64ForImage(string image)
        {
            StringBuilder sbText = new StringBuilder(image, image.Length);
            sbText.Replace("\r\n", String.Empty);
            sbText.Replace(" ", String.Empty);
            return sbText.ToString();
        }
    }
}
